<script>
/*
 * 色带选择器组件
 */
import DEFAULT_RIBBONS from './default-ribbons';

export default {
  props: {
    //色带列表，不设置为默认色带列表
    ribbonColors: {
      type: Array,
      default() {
        return DEFAULT_RIBBONS;
      },
    },
    //选择的色带，值可以是色带颜色列表，也可以是色带索引，如果是色带索引，外部组件结合DEFAULT_RIBBONS取颜色列表
    value: {
      type: [Array, Number],
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      currentIdx: -1, //当前选择的色带索引
    };
  },
  computed: {
    //当前色带渐进色样式
    currentRibbon() {
      let colors = typeof this.value === 'number' ? this.ribbonColors[this.value] : this.value;
      let strColor = colors.join(',');
      let targetColors = this.ribbonColors.find(p => p.join(',') == strColor);
      if (targetColors) {
        return this.getItemStyle(targetColors);
      }
      return {
        background: '#fffffff',
      };
    },
  },
  methods: {
    //获取色带颜色也不对应的色带渐进色样式
    getItemStyle(itemColors) {
      let linearColors = [];
      itemColors.forEach((item, index) => {
        linearColors.push(`${item} ${index / itemColors.length * 100}%`);
        linearColors.push(`${item} ${++index / itemColors.length * 100}%`);
      });
      return {
        background: `linear-gradient(to right, ${linearColors.join(',')})`,
      };
    },
    //选择色带
    selectItem(index) {
      if (index != this.currentIdx) {
        let data = typeof this.value === 'number' ? index : this.ribbonColors[index];
        this.$emit('input', data);
        this.$emit('on-change', this.ribbonColors[index]);
      }
      this.currentIdx = index;
    },
  },
};
</script>

<template>
  <Dropdown
    trigger="click"
    placement="bottom-start"
    class="ribbon-wrapper k-input-wrapper">
    <div class="k-input">
      <div
        :style="currentRibbon"
        class="ribbon-selection"
      ></div>
      <Icon
        type="arrow-down-b"
        class="k-input-icon k-input-icon-normal ribbon-drop-icon"></Icon>
    </div>
    <DropdownMenu slot="list">
      <DropdownItem
        v-for="(item,index) in ribbonColors"
        :key="index"
        :value="index"
        @click.native="selectItem(index)">
        <div
          :style="getItemStyle(item)"
          class="ribbon-drop-item"></div>
      </DropdownItem>
    </DropdownMenu>
  </Dropdown>
</template>

<style lang="less">
.ribbon-wrapper {
  width: 100%;
  .k-dropdown-rel {
    height: 32px;
  }
}
.ribbon-drop-icon {
  top: 0;
}
.ribbon-selection {
  position: absolute;
  top: 5px;
  right: 32px;
  left: 8px;
  bottom: 5px;
}
.ribbon-drop-item {
  height: 20px;
}
</style>
